<?php
include_once("model/dbConfig.php");
include_once("model/logicConfig.php");
include_once("model/itemConfig.php");
include_once("model/Page.php");
include_once("model/Menu.php");
include_once("model/IndexGallery.php");
include_once("model/User.php");
include_once("model/Organization.php");
include_once("model/Item.php");
include_once("model/Transaction.php");

class Model {
    private $_config;
     public  $auth = array ();
     public  $positions = array ();
	 
   public function __construct()  
    {
    	        global $config;
		        global $organizationType;
    
		
	
    //mysql_connect('localhost',$username,$password);
	$link =mysql_connect($config['host_address'],$config['username'],$config['password']);
    if (!$link) {
    die('Not connected : username:' .$username. mysql_error());
    }
		mysql_query("set characher set utf8");
		mysql_query("set names utf8");	
		$db_selected = mysql_select_db($config['database'], $link);
    if (!$db_selected)
        {
         die ("Can\'t use menu_item : " . mysql_error());
        }
      $organizations=$this->getOrganizations('all');
	  foreach($organizations as $org){
		$this->auth[$org->id]=$org->name;
	  }
	  $this->auth['all']='全部';
      $this->auth['management']='管理';
	  $this->auth['accounting']='财务部';
	  $this->auth['none']='无权限';
	 
    }
	
   function __destruct() {
  // echo "<br>destructor of model";
  echo "<div id='cn-toppage-foot'><a id ='bot' href='#top' title='Return to Top of Page'>Top of Page</a></div>";
  echo "<script type='text/javascript'>setCurrent();</script>";
  echo "<br>©2009-2012 珠海菲雪 服装公司 All Rights Reserved ";
   mysql_close();

   }
   
   	public function refresh($id){
   		
		if(isset($id)) {
		$setLogged= mysql_query("UPDATE `user` SET refresh_time=now() WHERE `id` = '$id'") or die(mysql_error());
		
		//add log
		}
	}
   
   public function getAllPositions(){
   	$sql="SELECT * 
	FROM  `_c_logic` 
	WHERE  `name` =  'positionType'";
	$result = mysql_query($sql);
	    $return = array ();
        while($row = mysql_fetch_array($result))
        {
        	$para=$row['para'];
        	$return[$para]=$row['value'];
        }
		return $return;
   }
   public function getReportName(){
	$sql="SELECT * 
	FROM  `_c_logic` 
	WHERE  `name` =  'reportType'";
	$result = mysql_query($sql);
	    $return = array ();
        while($row = mysql_fetch_array($result))
        {
        	$para=$row['para'];
        	$return[$para]=$row['value'];
        }
		return $return;
   }
   
   public function storedProcedure($spname,$parameters)
	{
		$sql="CALL `$spname` (";
		foreach($parameters as $p){
			$sql.="'".$p."',";
		}
		if(count($parameters)>0){
		$sql=substr($sql, 0, -1); 
		}
		$sql.=")";
		runtimelog( "storeprocedure".$sql);
		return mysql_query($sql);
		//$result = mysql_query($name);
	}
	public function getPageRid()
	{
	   $result = mysql_query("SELECT * FROM page_item ORDER BY `page_item`.`id` ASC ");
	  
       $return = array ();
      array_push($return, 0); // same as $call_trace[] = $name

      while($row = mysql_fetch_array($result))
      {
   	
      array_push($return, $row['rid']); // same as $call_trace[] = $name
     }
		return $return;
	}	
	public function getMenuList()
	{
		$result = mysql_query("SELECT * FROM menu_item ORDER BY `menu_item`.`id` ASC");
	    $return = array ();
        while($row = mysql_fetch_array($result))
        {
         array_push($return, new Menu( $row['id'],$row['rid'],$row['url'],$row['label'],$row['toid'],$row['detail'])); // same as $call_trace[] = $name
        }
		return $return;
	}
	
	public function getMenuRid()
	{
	   $result = mysql_query("SELECT * FROM menu_item ORDER BY `menu_item`.`id` ASC ");
	  
       $return = array ();
      array_push($return, 0); // same as $call_trace[] = $name

      while($row = mysql_fetch_array($result))
      {
   	
      array_push($return, $row['rid']); // same as $call_trace[] = $name
     }
		return $return;
	}	
	
	public function getIndexGalleryList()
	{
		$result = mysql_query("SELECT * FROM index_gallery ORDER BY `index_gallery`.`id` ASC");
	    $return = array ();
        while($row = mysql_fetch_array($result))
        {
         array_push($return, new IndexGallery( $row['id'],$row['rid'],$row['content'],$row['thumbnail'],$row['title'],$row['detail'])); // same as $call_trace[] = $name
        }
		return $return;
	}
	
	public function getIndexRid()
	{
	   $result = mysql_query("SELECT * FROM index_gallery ORDER BY `index_gallery`.`id` ASC ");
       $return = array ();
      array_push($return, 0);

      while($row = mysql_fetch_array($result))
      {
   	
      array_push($return, $row['rid']); // same as $call_trace[] = $name
     }
		return $return;
	}	
	
	public function getBook($title)
	{
		// we use the previous function to get all the books and then we return the requested one.
		// in a real life scenario this will be done through a db select command
		$allBooks = $this->getBookList();
		return $allBooks[$title];
	}
	
	public function getImgList($pageManage){
					$return=array();
					
					
					foreach($pageManage as $page){
						
						$name= $page->name;
						$array=$this->getFileList("../images/".$name."/");
					    $return[$name]=$array;
				   }
					
		
	        return $return;
    }
	
	function getFileList($dir)
  {
    // array to hold return value
    $retval = array();

    // add trailing slash if missing
    if(substr($dir, -1) != "/") $dir .= "/";

    // open pointer to directory and read list of files
    $d = @dir($dir) or die("getFileList: Failed opening directory $dir for reading");
    while(false !== ($entry = $d->read())) {
      // skip hidden files
      if($entry[0] == ".") continue;
      if(is_dir("$dir$entry")) {
        $retval[] = array(
          "name" => "$entry/",
          "path" => "$dir$entry/",
          "type" => filetype("$dir$entry"),
          "size" => 0,
          "lastmod" => filemtime("$dir$entry")
        );
      } elseif(is_readable("$dir$entry")) {
        $retval[] = array(
          "name" => "$entry",
          "path" => "$dir$entry",
          "type" => mime_content_type("$dir$entry"),
          "size" => filesize("$dir$entry"),
          "lastmod" => filemtime("$dir$entry")
        );
      }
    }
    $d->close();

    return $retval;
  }

 function getAccount($name){
 	 $this->positions=$this->getAllPositions();
	$result = mysql_query("SELECT * FROM user WHERE name='$name'");
       $row = mysql_fetch_array($result);
	   
         $return = new User($row['id'],
         					$row['name'],
         					$row['real_name'],
         					$row['authority'],
         					$row['password'],
         					$row['online'],
         					$row['session'],
         					$row['email'],
         					$row['phone_number'],
         					$row['work_address'],
         					$this->auth,
         					$this->getPosition($row['position']),
							$row['ip'],
							$row['os'],
							$row['browser']);
        
		return $return;
 }
 
  function getAccountById($id){
  	 $this->positions=$this->getAllPositions();
	$result = mysql_query("SELECT * FROM user WHERE id='$id'");
       $row = mysql_fetch_array($result);
         $return = new User(
         					$row['id'],
         					$row['name'],
         					$row['real_name'],
         					$row['authority'],
         					$row['password'],
         					$row['online'],
         					$row['session'],
         					$row['email'],
         					$row['phone_number'],
         					$row['work_address'],
         					$this->auth,
         					$this->getPosition($row['position']),
							$row['ip'],
							$row['os'],
							$row['browser']);
        
		return $return;
 }
	
	 function getAllAccount(){
	$result = mysql_query("SELECT * FROM user WHERE id>0");
	 $this->positions=$this->getAllPositions();
	$return = array ();
        while($row = mysql_fetch_array($result))
        {
         array_push($return, new User(
					         $row['id'],$row['name'],
					         $row['real_name'],
					         $row['authority'],
					         $row['password'],
					         $row['online'],
					         $row['session'],
					         $row['email'],
					         $row['phone_number'],
					         $row['work_address'],
				          	$this->auth,
				          	$this->getPosition($row['position']),
							$row['ip'],
							$row['os'],
							$row['browser'])
		  ); // same as $call_trace[] = $name
        }
		return $return;
 }
	public function getPosition($pos){
		if($pos==""){
			return "无";
		}
		 $posArray=explode(",", $pos);
		 $return=array();
		 foreach($posArray as $v){
		 	array_push($return,$this->positions[$v]);
		 }
		 
		 return implode(",", $return);
	}
	

	
function getAllItem(){
	$result = mysql_query("SELECT * FROM item");
	$return = array ();
        while($row = mysql_fetch_array($result))
        {
         array_push($return, new Item($row['scan_code'],$row['product_code'],$row['designer_code'],$row['type'],$row['year'],$row['season'],$row['flow'],$row['material'],$row['color'],$row['size'],$row['designer'],$row['name'],$row['price'],$row['ratio'],$row['active'])); // same as $call_trace[] = $name
        }
		return $return;	
 }
function getOrganizations($option){
	if($option=='all'){
	 		$sql="SELECT * FROM organization WHERE id>0";
 	}elseif($option=='w'){
	 		$sql="SELECT * FROM organization WHERE id>0 AND type='w'";
 	}elseif(!is_array($option)){
	 			 		$sql="SELECT * FROM organization WHERE id='$option'";
						$result=mysql_query($sql);
						$row = mysql_fetch_array($result);
						return new Organization($row['id'],$row['name'],$row['type'],$row['des']);
			
    }else{
	
	 	$sql="SELECT * FROM organization WHERE ";
		foreach($option as $opt){
			$sql.="id='$opt',";
		}
		$sql = substr($sql, 0, -1); 		
    }
    $result=mysql_query($sql);
	$return = array ();
        while($row = mysql_fetch_array($result))
        {
         array_push($return, new Organization($row['id'],$row['name'],$row['type'],$row['des'])); // same as $call_trace[] = $name
        }
		return $return;
	
 
    }


function getItem($scan_code){//removed auto create functionality
	$sql="SELECT * FROM item WHERE scan_code='$scan_code'";
	    $result=mysql_query($sql);
	$num_rows = mysql_num_rows($result);
	if($num_rows==0){
		return NULL;
	}elseif($num_rows==1){
		$row = mysql_fetch_array($result);
		return new Item($row['scan_code'],$row['product_code'],$row['designer_code'],$row['type'],$row['year'],$row['season'],$row['flow'],$row['material'],$row['color'],$row['size'],$row['designer'],$row['name'],$row['price'],$row['ratio'],$row['active']);   
	}else{
		return -1;
		//something wrong
	}
	
	
	
	
 
    }

function getInventory($orids,$scan_codes,$min,$max,$start,$end){
	
	
	$resO="";//orgainization id
    $resS="";//scan code
    $resN="";//number
	$resT="";//time

	
	if(isset($orids)){
		if(is_array($orids)){
			$resO="AND (";
				foreach($orids as $orid){
					$resO=$resO." orid='$orid' OR";
				}
			$resO=substr($resO,0,-2);
		$resO=$resO.")";
		}else{
			$resO="AND (orid='$orids')";
		}
	}
	if(isset($scan_codes)){
		if(is_array($scan_codes)){
	   $resS="AND (";
				foreach($scan_codes as $scan_code){
					$resS=$resS." scan_code='$scan_code' OR";
				}
			$resS=substr($resS,0,-2);
		$resS=$resS.")";
			
		}else{
			$resS="AND (scan_code='$scan_codes')";
		}
	}
	
    if(isset($min)&&isset($max)){
			$resN="AND (number>='$min' AND number<='$max')";
	}elseif(isset($min)&&!isset($max)){
			$resN="AND (number>='$min')";
	}elseif(!isset($min)&&isset($maxNum)){
			$resN="AND (number<='$max')";
	}
    
    if(isset($start)&&isset($end)){
	       $start=$start." 00:00:00";
	       $end=$end." 23:59:59";
		   $resT="AND (time_stamp>'$start' AND time_stamp<'$end')";
	}

	
	$condition=$resO.$resS.$resN.$resT;
	if($condition!=""){
	    $condition=substr($condition, 3,strlen($condition)-2);  //
	}else{
		$condition=1;
    }
		
	$sql="SELECT  
          i.`id` as id,   
          i.`orid` as orid,   
          o.`name` as name,
          i.`scan_code` as scan_code,   
          i.`number` as number,    
          i.`time_stamp` as time_stamp
          FROM inventory i 
          INNER JOIN organization o ON i.`orid`= o.`id`
          WHERE $condition ORDER BY time_stamp DESC";
//echo $sql."<br><br>";
		 $result=mysql_query($sql);
	     $return = array ();
        while($row = mysql_fetch_array($result))
        {	     
         $scan_code=$row['scan_code'];
         
        	$inv = array(
    "id" => $row['id'],
    "name" => $row['name'],
    "orid" => $row['orid'],
     "number" => $row['number'],
    "time_stamp" => $row['time_stamp'],
     "item" => $this->getItem($scan_code)
            );
         array_push($return, $inv);
        }
		return $return;
	
}



function getPendingTransactionsByOrid($orid,$type){
	$sql="SELECT 
t.`id` as id, 
t.`scan_code` as scan_code,
t.`action` as action,
t.`confirm` as confirm,
o1.`name` as source,
o2.`name` as target,
u1.`name` as user1,
t.`amount` as amount,
t.`income` as income,
t.`begin_time_stamp` as begin_time_stamp,
t.`finish_time_stamp` as finish_time_stamp
                            FROM transaction t
                           INNER JOIN user u1 ON t.`user1`= u1.`id`
                           INNER JOIN organization o1 ON t.`source`= o1.`id`
                           INNER JOIN organization o2 ON t.`target`= o2.`id`
                           WHERE  target='$orid' AND confirm =0  AND action='$type' ORDER BY id DESC";
						   
	$result = mysql_query($sql);
	
	$return = array ();
        while($row = mysql_fetch_array($result))
        {
         array_push($return, new Transaction($row['id'],$row['scan_code'],$row['source'],$row['target'],$row['action'],$row['confirm'],$row['user1'],'',$row['amount'],$row['income'],$row['begin_time_stamp'],$row['finish_time_stamp'])  ); // same as $call_trace[] = $name
        }
		return $return;
}

function getFinacialTransactions($actions,$orids,$start,$end,$minimal,$maximal,$minNum,$maxNum,$scan_codes,$confirm){
	$resAC="";	
	$resO="";//orgainization id
	$resT="";//time
	$resN="";//number
	$resA="";//money amount
	$resS="";//scan code
	$resC="";

	if(isset($actions)){
		if(is_array($actions)){
			$resAC="AND (";
				foreach($actions as $action){
					
					$resAC=$resAC." action='$action' OR";
				}
			$resAC=substr($resAC,0,-2);
		$resAC=$resAC.")";
					
				
			
		}else{
			$resAC="AND (action='$actions')";
		}
	}
	
	
	if(isset($orids)){
		if(is_array($orids)){
			$resO="AND (";
				foreach($orids as $orid){
					$resO=$resO." source='$orid' OR target='$orid' OR";
				}
			$resO=substr($resO,0,-2);
		$resO=$resO.")";
					
				
			
		}else{
			$resO="AND (source='$orids' OR target='$orids')";
		}
		
		
		
	}
	if(isset($confirm)){
		if(is_array($confirm)){
	         $resC="AND (";
			foreach($confirm as $c){
				$resC=$resC." confirm='$c' OR";
			}
			 $resC=substr($resC,0,-2);
		     $resC=$resC.")";
		}else{
			$resC="AND (confirm='$confirm')";
		}
	}		
	
	if(isset($scan_codes)){
		if(is_array($scan_codes)){
	         $resS="AND (";
			foreach($scan_codes as $scan_code){
				$resS=$resS." scan_code='$scan_code' OR";
			}
			 $resS=substr($resS,0,-2);
		     $resS=$resS.")";
			}else{
			$resS="AND (scan_code='$scan_codes')";
		}
	}						

	if(isset($start)&&isset($end)){
	$start=$start." 00:00:00";
	$end=$end." 23:59:59";
		
			$resT="AND (begin_time_stamp>'$start' AND begin_time_stamp<'$end')";

	}						
	
    if(isset($minimal)&&isset($maximal)){
	
		
			$resA="AND (income>='$minimal' AND income<='$maximal')";

	}elseif(isset($minimal)&&!isset($maximal)){
					$resA="AND (income>='$minimal')";
		
	}elseif(!isset($minimal)&&isset($maximal)){
					$resA="AND (income<='$maximal')";
		
	}
    
	if(isset($minNum)&&isset($maxNum)){
	
		
			$resN="AND (amount>='$minimal' AND amount<='$maximal')";

	}elseif(isset($minNum)&&!isset($maxNum)){
					$resN="AND (amount>='$minNum')";
		
	}elseif(!isset($minNum)&&isset($maxNum)){
					$resN="AND (amount<='$maxNum')";
		
	}
	
	

	$condition=$resAC.$resO.$resT.$resN.$resA.$resS.$resC;
	if($condition!=""){
	    $condition=substr($condition, 3,strlen($condition)-2);  //
	}else{
		$condition=1;
    }
	$sql="SELECT 
t.`id` as id, 
t.`scan_code` as scan_code,
t.`action` as action,
t.`confirm` as confirm,
o1.`name` as source,
o2.`name` as target,
u1.`name` as user1,
u2.`name` as user2,
t.`amount` as amount,
t.`income` as income,
t.`begin_time_stamp` as begin_time_stamp,
t.`finish_time_stamp` as finish_time_stamp,
t.`code` as code
                            FROM transaction t
                           INNER JOIN user u1 ON t.`user1`= u1.`id`
                           INNER JOIN user u2 ON t.`user2`= u2.`id`
                           INNER JOIN organization o1 ON t.`source`= o1.`id`
                           INNER JOIN organization o2 ON t.`target`= o2.`id`
                           WHERE $condition ORDER BY id DESC ";
						   runtimelog( "getFinacialTransactions".$sql);
	$result = mysql_query($sql);
	//SELECT *  FROM `transaction` WHERE `begin_time_stamp` < '2012-10-06 09:51:32	'
	$return = array ();
        while($row = mysql_fetch_array($result))
        {
         array_push($return, new Transaction($row['id'],$row['scan_code'],$row['source'],$row['target'],$row['action'],$row['confirm'],$row['user1'],$row['user2'],$row['amount'],$row['income'],$row['begin_time_stamp'],$row['finish_time_stamp'],$row['code'])  ); // same as $call_trace[] = $name
        }
		return $return;
	
 
 }

}

?>

